package cn.dnui_wwt524.dnuifood_16110100524.controller;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import cn.dnui_wwt524.dnuifood_16110100524.R;
import cn.dnui_wwt524.dnuifood_16110100524.bean.BuyBean;
import cn.dnui_wwt524.dnuifood_16110100524.listener.OnRetrofitListener;
import cn.dnui_wwt524.dnuifood_16110100524.model.BuyModel;

public class BuyActivity extends BaseActivity implements OnRetrofitListener<BuyBean> {
    private EditText num,adress,suggesttime;
    private TextView name,sum;
    private Button buy;
    private String shop_id;
    private String food_name;
    private String price;
    private String food_id;
    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        shop_id = getIntent().getStringExtra("shop_id");
        food_name = getIntent().getStringExtra("food_name");
        price = getIntent().getStringExtra("price");
        food_id=getIntent().getStringExtra("food_id");
        Toast.makeText(this, price, Toast.LENGTH_SHORT).show();
        initViews();
        initDate();
        initEvents();
    }

    @Override
    void initViews() {
        layout_file= R.layout.activity_buy;
        setLayout(layout_file);

        buy=findViewById(R.id.buy_button);
        num=findViewById(R.id.buy_num);
        adress=findViewById(R.id.buy_adress);
        suggesttime=findViewById(R.id.buy_time);
        name=findViewById(R.id.buy_name);
        sum=findViewById(R.id.buy_sum);
    }

    @Override
    void initEvents() {
        buy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                buy_food();
            }
        });
    }

    private void buy_food() {
        sharedPreferences=getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        String user_id = sharedPreferences.getString("user_id","user_id");

        BuyModel buyModel=new BuyModel();
        buyModel.insertOrder(user_id,food_id,"1",price,suggesttime.getText().toString(),adress.getText().toString(),this);
    }

    @Override
    void initDate() {
        sum.setText("总价:"+price);
        name.setText(food_name);
    }

    @Override
    public void onSuccess(BuyBean object, int flag) {
        if(object.getSuccess().equals("1")){
            Toast.makeText(BuyActivity.this,"购买成功",Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(BuyActivity.this,"购买失败",Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onFailure(String msg) {
        Toast.makeText(BuyActivity.this,"联网失败",Toast.LENGTH_SHORT).show();
    }
}
